using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.Common;
using EnvDTE;
using VSLangProj;
using System.Runtime.Serialization; 

namespace Microsoft.Practices.RepositoryFactory.References
{
    /// <summary>
    /// UnBoundRecipeReference that allows to be executed only on a FileCodeModel on the DataContracts project
    /// </summary>
    [Serializable]
    public class FileCodeModelReference : UnboundRecipeReference
    {
        /// <summary>
        /// UnBoundRecipeReference that allows to be executed only on a FileCodeModel on the DataContracts project
        /// </summary>
        public FileCodeModelReference(string recipe) 
            : base(recipe)
        {
        }

        /// <summary>
        /// Required constructor for deserialization.
        /// </summary>
        protected FileCodeModelReference(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// See <see cref="P:Microsoft.Practices.RecipeFramework.IAssetReference.AppliesTo"/>.
        /// </summary>
        /// <value></value>
        public override string AppliesTo
        {
            get { return Properties.Resources.FileCodeModelReference; }
        }

        /// <summary>
        /// Performs the validation of the item passed as target
        /// Returns true if the reference is allowed to be executed in the target
        /// that is if the target is a FileCodeModel file.
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public override bool IsEnabledFor(object target)
        {
            ProjectItem item = target as ProjectItem;
            const string propertyName = "IsWCFDataContractsProject";

            if(item != null && item.FileCodeModel != null)
            {
                Project project = item.ContainingProject;

                try
                {
                    if(project.Globals.get_VariableExists(propertyName))
                    {
                        string propertyValue = (string)project.Globals[propertyName];
                        bool propertyValueBoolean;

                        if(Boolean.TryParse(propertyValue, out propertyValueBoolean))
                        {
                            return propertyValueBoolean;
                        }
                    }
                }
                catch
                {
                    return false;
                }
            }

            return false;
        }
    }
}